<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>消息通知</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div v-if="filteredNotifications.length > 0" class="notifications-list">
          <div 
            v-for="notification in filteredNotifications" 
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': notification.unreadPop < 3 }"
          >
            <div class="notification-content">
              <p>{{ notification.content }}</p>
              <span class="notification-time">{{ formatDateTime(notification.createTime) }}</span>
            </div>
            <button 
              v-if="notification.unreadPop < 3" 
              class="mark-read-btn"
              @click="handleMarkAsRead(notification)"
            >
              标记已读
            </button>
          </div>
        </div>
        <div v-else class="empty-state">
          暂无新消息
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { API_CONFIG } from '../config/apiConfig';
import { ToastService } from '../utils/toastService';

interface Notification {
  id: number | string;
  content: string;
  read: boolean;
  unreadPop: number;
  createTime: string;
  type?: string;
}

const props = defineProps<{
  show: boolean;
  notifications: Notification[];
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'read', notification: Notification): void;
}>();

// 过滤掉 unreadPop 为 3 的消息
const filteredNotifications = computed(() => {
  return props.notifications.filter(notification => notification.unreadPop < 3);
});

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 处理关闭模态框
const handleClose = () => {
  emit('close');
};

// 处理标记已读
const handleMarkAsRead = async (notification: Notification) => {
  try {
    // 确保 id 是字符串类型，因为 API 路径需要字符串
    const notificationId = notification.id.toString();
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/message-notification/read/${notificationId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    });

    const result = await response.json();
    if (result.code === 0 || result.code === '0') {
      // 更新本地状态
      emit('read', notification);
      
      // 可选：显示成功提示
      console.log('消息已标记为已读');
    } else {
      ToastService.error('标记已读失败，请重试');
    }
  } catch (error) {
    console.error('标记已读请求失败:', error);
    ToastService.error('标记已读失败，请检查网络连接');
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  max-height: calc(80vh - 120px);
}

.notifications-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.notification-item {
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.notification-item.unread {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.notification-content {
  flex: 1;
}

.notification-content p {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
}

.notification-time {
  color: #999;
  font-size: 12px;
}

.mark-read-btn {
  padding: 6px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  white-space: nowrap;
  transition: all 0.3s;
}

.mark-read-btn:hover {
  background-color: #40a9ff;
}

.empty-state {
  text-align: center;
  color: #999;
  padding: 32px;
  font-size: 14px;
}
</style>